package com.camel.base.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.camel.base.enums.DataSource;
import com.camel.base.enums.NumberNature;
import com.camel.base.feign.CtiManagerService;
import com.camel.base.feign.SysCompanyService;
import com.camel.base.model.ZsNumberCompany;
import com.camel.base.model.ZsPstnnumber;
import com.camel.base.service.ZsNumberCompanyService;
import com.camel.base.service.ZsPstnnumberService;
import com.camel.core.controller.BaseCommonController;
import com.camel.core.entity.IFilter;
import com.camel.core.entity.IParams;
import com.camel.core.entity.Result;
import com.camel.core.exceptions.CustomException;
import com.camel.core.service.BaseCommonService;
import com.camel.core.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author camel
 */
@RestController
@RequestMapping("zsPstn")
public class ZsPstnnumberController extends BaseCommonController<ZsPstnnumber> {

    @Autowired
    private SysCompanyService companyService;

    @Autowired
    private ZsNumberCompanyService<ZsNumberCompany> numberCompanyService;

    @Autowired
    private CtiManagerService ctiManagerService;

    @Autowired
    private ZsPstnnumberService<ZsPstnnumber> service;

    @Override
    public Result index(@RequestBody IParams params) {
        // 设置默认筛选项
        boolean hasDefault = false;
        for (IFilter filter : params.getFilters()) {

            if ("belongUser".equals(filter.getFieldName())) {
                if (!StpUtil.hasRole("admin")) {
                    filter.setCompare("=");
                    filter.setFieldValue(StpUtil.getLoginIdAsInt());
                    hasDefault = true;
                } else {
                    params.getFilters().remove(filter);
                }
                break;
            }
        }
        if (!StpUtil.hasRole("admin") && !hasDefault) {
            IFilter iFilter = new IFilter("belongUser", "=", StpUtil.getLoginIdAsInt());
            params.getFilters().add(iFilter);
        }
        return super.index(params);
    }

    @Override
    public boolean deleteAble(Serializable id) {
        ZsPstnnumber detail = getiService().getById(id);
        if (ObjectUtils.isEmpty(detail)) {
            throw new CustomException("删除失败: 外呼号已经删除");
        }
        // 查询分配记录
        int count = numberCompanyService.count(new QueryWrapper<ZsNumberCompany>().eq("number_id", id));
        if (count > 0) {
            throw new CustomException("删除失败: 外呼号已经被分配请回收后重试");
        }
        return true;
    }

    @Override
    public Result save(@RequestBody ZsPstnnumber entity) {
        // 页面提交后默认为数据来源为系统创建
        entity.setSource(DataSource.SYSTEM.getValue());
        entity.setBelongUser(StpUtil.getLoginIdAsInt());
        Result pstNumber = ctiManagerService.createPstNumber(entity);
        if(pstNumber.isSuccess()) {
            return super.save(entity);
        }
        return pstNumber;
    }

    /**
     * 分配热线号码
     * @return
     */
    @PostMapping("/allocation")
    public Result allocation(@RequestBody ZsPstnnumber entity) {
        Result result = ctiManagerService.hotPstNumber(entity);
        if(result.isSuccess()) {
            return update(entity);
        }
        return ResultUtil.error("分配失败！");
    }

    @PostMapping("/auth")
    public Result auth(@RequestBody ZsPstnnumber entity) {
        if (ObjectUtils.isEmpty(entity.getCompanyId())) {
            throw new CustomException("未选择授权公司");
        }
        int count = numberCompanyService.count(new QueryWrapper<ZsNumberCompany>().eq("number_id", entity.getId()).eq("company_id", entity.getCompanyId()));
        if(count > 0) {
            return ResultUtil.error(500, "授权失败：重复的授权。");
        }
        Result details = companyService.details(entity.getCompanyId());
        if (!ObjectUtils.isEmpty(details.jsonObject())) {
            ZsNumberCompany zsNumberCompany = new ZsNumberCompany();
            zsNumberCompany.setCompanyId(entity.getCompanyId());
            zsNumberCompany.setCompanyName(details.jsonObject().getString("name"));
            zsNumberCompany.setNumber(entity.getPstnnumber());
            zsNumberCompany.setNumberId(entity.getId());
            zsNumberCompany.setNumber(entity.getPstnnumber());
            numberCompanyService.save(zsNumberCompany);
            return ResultUtil.success("授权成功");
        }
        return ResultUtil.error(500, "公司数据不正确");
    }

    @PostMapping("/sync")
    public Result sync() {
        Result result = ctiManagerService.getpstnnumber(new JSONObject());
        if (result.isSuccess()) {
            List<ZsPstnnumber> allNumbers = service.list();

            List<LinkedHashMap<String, String>> list = (ArrayList<LinkedHashMap<String, String>>) result.getData();
            if (CollectionUtils.isEmpty(allNumbers)) {
                for (LinkedHashMap<String, String> phone : list) {
                    ZsPstnnumber zsPstnnumber = new ZsPstnnumber();
                    zsPstnnumber.setPstnnumber(phone.get("pstnNumber"));
                    zsPstnnumber.setSource(1);
                    zsPstnnumber.setNature(NumberNature.PUBLIC_NUMBER);
                    zsPstnnumber.setRemark(phone.get("displayName"));
                    zsPstnnumber.setGateway(phone.get("gateWay"));
                    service.save(zsPstnnumber);
                }
                return ResultUtil.success();
            }
            List<String> numbers = allNumbers.stream().map(ZsPstnnumber::getPstnnumber).collect(Collectors.toList());
            for (LinkedHashMap<String, String> phone : list) {
                if (!numbers.contains(phone.get("pstnNumber"))) {
                    ZsPstnnumber zsPstnnumber = new ZsPstnnumber();
                    zsPstnnumber.setPstnnumber(phone.get("pstnNumber"));
                    zsPstnnumber.setSource(1);
                    zsPstnnumber.setGateway(phone.get("gateWay"));
                    zsPstnnumber.setNature(NumberNature.PUBLIC_NUMBER);
                    service.save(zsPstnnumber);
                }
            }
            return ResultUtil.success();
        }
        return ResultUtil.error(500, result.getMsg());
    }

    @Override
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Serializable id) {
        ZsPstnnumber ps = service.getById(id);
        if(ObjectUtils.isEmpty(ps)) {
            return ResultUtil.error("外呼号码不存在！");
        }
        ctiManagerService.deletePstNumber(ps);
        return super.delete(id);
    }

    @Override
    public BaseCommonService<ZsPstnnumber> getiService() {
        return service;
    }

    @Override
    public String getMouduleName() {
        return "外线号码";
    }
}
